package com.tuyan.aixiang.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import com.google.gson.Gson;

/**
 * unit convert
 */
public class ConvertUtil {

    private static  Gson gson = new Gson();

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String obj2str(Object object) {
        try {
            return gson.toJson(object);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T str2obj(String str, Class<T> clazz) {
        try {
            return gson.fromJson(str, clazz);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * base64 to bitmap
     */
    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string.split(",")[1], Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}
